package cn.fyl.pet.service.impl;

import cn.fyl.basic.RocketMq.RocketMQProducer;
import cn.fyl.basic.exception.BusinessException;
import cn.fyl.basic.service.IBaiduAiAuditService;
import cn.fyl.basic.util.CodeGenerateUtils;
import cn.fyl.basic.util.DistanceUtils;
import cn.fyl.basic.util.PageList;
import cn.fyl.basic.util.Point;
import cn.fyl.order.domain.OrderPetAcquisition;
import cn.fyl.order.mapper.OrderPetAcquisitionMapper;
import cn.fyl.org.domain.Employee;
import cn.fyl.org.domain.Shop;
import cn.fyl.org.mapper.EmployeeMapper;
import cn.fyl.org.mapper.ShopMapper;
import cn.fyl.pet.domain.Pet;
import cn.fyl.pet.domain.SearchMasterMsg;
import cn.fyl.pet.domain.SearchMasterMsgAuditLog;
import cn.fyl.pet.dto.OrderDto;
import cn.fyl.pet.mapper.PetMapper;
import cn.fyl.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.fyl.pet.mapper.SearchMasterMsgMapper;
import cn.fyl.pet.query.SearchMasterMsgQuery;
import cn.fyl.pet.service.ISearchMasterMsgService;
import cn.fyl.basic.service.impl.BaseServiceImpl;
import cn.fyl.user.domain.User;
import cn.fyl.user.mapper.UserMapper;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private RocketMQProducer rocketMQProducer;

    @Override
    public void publish(SearchMasterMsg searchMasterMsg, Long id) {
        //1.先添加到数据库t_searchMasterMsg    state:0 待审核
        // user_id   shop_id
        // 通过logininfoid查询userid
        User user = userMapper.loadByLoginInfoId(id);
        searchMasterMsg.setUserId(user.getId());

        //  shop_id: 先计算最近店铺
        // 获取当前地址的point
        Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
        Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());

        searchMasterMsg.setShopId(nearestShop.getId());

        searchMasterMsgMapper.save(searchMasterMsg);

        // 审核文本
        Boolean text = baiduAiAuditService.textAudit(searchMasterMsg.getTitle()+searchMasterMsg.getAddress() + searchMasterMsg.getName() + searchMasterMsg.getAddress());

        // 审核图片
        //Boolean img = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());

        if(text){ // 审核成功
            // 改变状态
            searchMasterMsg.setState(1);
            searchMasterMsg.setNote("待处理");
            searchMasterMsgMapper.update(searchMasterMsg);

            SearchMasterMsgAuditLog smmal = new SearchMasterMsgAuditLog();
            smmal.setNote("待处理");
            smmal.setState(1);
            smmal.setAuditTime(new Date());
            smmal.setMsgId(searchMasterMsg.getId());

            searchMasterMsgAuditLogMapper.save(smmal);

        }else { //审核失败


            searchMasterMsg.setNote("信息异常");
            searchMasterMsgMapper.update(searchMasterMsg);

            SearchMasterMsgAuditLog smmal = new SearchMasterMsgAuditLog();
            smmal.setNote("审核不通过");
            smmal.setState(0);
            smmal.setAuditTime(new Date());
            smmal.setMsgId(searchMasterMsg.getId());

            searchMasterMsgAuditLogMapper.save(smmal);
            throw new BusinessException("信息异常，请重新输入");

        }

    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, Long id) {
        Employee emp = employeeMapper.loadByLogininfoId(id);
        query.setState(1);
        if(emp.getShop_id()!=null){
            query.setShopId(emp.getShop_id());
        }

        return super.queryData(query);
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, Long id) {
        User user = userMapper.loadByLoginInfoId(id);
        query.setUserId(user.getId());
        return super.queryData(query);
    }

    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    public void accept(OrderDto dto) {
        Long handler = dto.getHandler();
        Long msgId = dto.getMsgId();
        String note = dto.getNote();
        // 根据smmid查询订单，如果查的到，该订单正在处理中，
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadBySmmId(msgId);
        if(order!=null){ // 之前接单了
            throw  new BusinessException("订单正在处理中。。。！");
        }



        // 通过searchMasterMsg生成一个pet
        // 获取寻主信息
        SearchMasterMsg smm = searchMasterMsgMapper.loadById(msgId);
        //创建pet信息
        Pet pet = searchMasterMsg2Pet(smm);
        petMapper.save(pet);
        // 生成收购订单
        OrderPetAcquisition opa = initOrderPetAcquisition(dto,pet,smm);
        // 保存订单
        orderPetAcquisitionMapper.save(opa);

        rocketMQProducer.sendDelayMsg(opa.getOrderSn(),3);
        System.out.println("延迟消息");



    }

    private OrderPetAcquisition initOrderPetAcquisition(OrderDto dto, Pet pet, SearchMasterMsg smm) {
        OrderPetAcquisition opa = new OrderPetAcquisition();
        // 使用工具类随机生成一个订单号
        String s = CodeGenerateUtils.generateOrderSn(smm.getUserId());
        opa.setOrderSn(s);
        // 摘要
        opa.setDigest("【"+smm.getTitle()+"】");
        // 最后确认时间
        opa.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));

        opa.setState(0);// 待处理
        opa.setPrice(smm.getPrice());
        opa.setPetId(pet.getId());
        opa.setUserId(smm.getUserId());
        opa.setShopId(smm.getShopId());
        opa.setAddress(smm.getAddress());
        opa.setEmpId(dto.getHandler());
        opa.setSearchMasterMsgId(dto.getMsgId());
        return opa;
    }

    private Pet searchMasterMsg2Pet(SearchMasterMsg smm) {
        Pet pet = new Pet();
        pet.setName(smm.getName());
        pet.setCostprice(smm.getPrice());
        pet.setType_id(smm.getPetType());
        pet.setResources(smm.getResources());
        pet.setShop_id(smm.getShopId());
        pet.setSearch_master_msg_id(smm.getId());
        return pet;
    }


}
